package com.greateamd.timetableasy.client.widgets.campus;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ListBox;
import com.greateamd.timetableasy.client.services.promotion.PromotionService;
import com.greateamd.timetableasy.client.services.promotion.PromotionServiceAsync;
import com.greateamd.timetableasy.client.services.util.ServerCall;
import com.greateamd.timetableasy.domain.Promotion;

public class PromotionListBox extends ListBox{

	private List<Promotion> promotions;
	
	public @UiConstructor PromotionListBox(boolean autoLoad) {
		if(autoLoad){
			loadPromotion();
		}
	}	

	public void loadPromotion() {
		final PromotionServiceAsync promotionService = GWT.create(PromotionService.class);
		new ServerCall<List<Promotion>>() {

			@Override
			protected void callService(AsyncCallback<List<Promotion>> asyncCallback) {
				promotionService.getAll(asyncCallback);
			}

			@Override
			public void onSuccess(List<Promotion> list) {
				promotions = list;
				showList();
			}
		}.call();
	}

	protected void showList() {
		clear();
		for(Promotion promotion : promotions){
			addItem(promotion.getName());
		}
	}
	
	public Promotion getSelectedPromotion(){
		if(getSelectedIndex()!= -1){
			return promotions.get(getSelectedIndex());
		}
		return null;
	}

	public void setSelectedPromotion(Promotion promotionToSelect){
		if(promotions.contains(promotionToSelect)){
			setSelectedIndex(promotions.indexOf(promotionToSelect));
		}
	}
	
	protected void setPromotions(List<Promotion> promotions) {
		this.promotions = promotions;
	}
}
